/* 
 *  @module Message
 *  Author: Alex Hu
 *
 *  Example:
 *
 *
 */


'use strict';

GML.Msg = (function(){
    
    var M = {};

    M.init = function(){
        $(document).on('click', '[role=refresh-mailbox]', function(e){
            M.freshUnread();
            e.preventDefault();
        });
    }

    M.render = function(c){
        var config = c
            , label = config.label
            // , filter = config.filter || []
            , manage = config.manage || []
            // , _filter = {}
            // , _checkbox = []
            // , _text = []
            // , _select = []
            , i, item, unreadNO
            , that = M
            , $filter = $('#filter_' + label + '_MSG')
            , $BOSS = $('#boss_' + label + '_MSG')
            , $pickAll = $('#pickAll_' + label + '_MSG')
            , $RT = GML.RT
            ;

        // config['table'] = $('#bodyTable' + label + 'MSG');
        config['element'] = {
            'pickAll': $pickAll,
            'pageNavS': $('#pageNavS_' + label + '_MSG'),
            'pageNav': $('#pageNav_' + label + '_MSG'),
            'bodyTable': $('#bodyTable_' + label + '_MSG'),
            'notice': $('#notice_' + label + '_MSG'),
            'calendar': {
                'before': $('[role~=before-F-MSG]', $filter),
                'after': $('[role~=after-F-MSG]', $filter)
            },
            'filter': $filter,
        };
        config["FN"] = {
            "refresh": function(){
                that.fire($BOSS);
            }
        };
        config["addition"] = config.addition;

        that.UI($filter);

        config['basket'] = [];
        if(!config['page']){
            config['page'] = {};
        }
        config['TO'] = {};
        unreadNO = config.unreadNO;
        if(unreadNO){
            that.unreadNO = unreadNO;
        }

        if(!config.namespace){
            config["namespace"] = {};
        }
        $BOSS.data('config', config);

        that.freshUnread();

        for(i = 0; i<manage.length; i++){
            item = manage[i];
            that.manage(item, $BOSS);
        }

        /* paging trigger */
        $BOSS.on('click', '[role~=page-MSG]', function(e){
            var $this = $(this);

            that.fire($this, $this.attr('href'), 1);
            e.preventDefault();
        });

        if($filter.length){
            // $BOSS.on('keyup', '[role~=keyword-F-MSG]', function(e){
            $filter.find('[role~=keyword-F-MSG]').keyup(function(e){
                var $this = $(this)
                    , $BOSS, url, param
                    ;

                if(e.keyCode === 13){
                    $BOSS = $this.closest('[role=bossMSG]');
                    config = $BOSS.data('config');
                    url = config.url;
                    param = that.paramFilter($BOSS);
                    if(param){
                        if(url.indexOf('?') > -1){
                            url += '&';
                        }else if(param){
                            url += '?';
                        }
                        url += param;
                    }
                    that.fire($this, url);
                }
                e.preventDefault();
            });

            $BOSS.on('click', '[role~=filter-MSG]', function(e){
                var $this = $(this)
                    , $BOSS = $this.closest('[role=bossMSG]')
                    , config = $BOSS.data('config')
                    , url = config.url
                    , param = that.paramFilter($BOSS)
                    ;

                if(param){
                    if(url.indexOf('?') > -1){
                        url += '&';
                    }else if(param){
                        url += '?';
                    }
                    url += param;
                }
                that.fire($this, url);
                e.preventDefault();
            });
        }

        // $BOSS.on('click', '[role=pickAll-MSG]', function(e){
        $pickAll.click(function(e){
            var unit, add
                , that = M
                , $this = $(this)
                , config = $this.closest('[role=bossMSG]').data('config')
                , $list = config.element.bodyTable.children()
                , itemCheckedClassName = "ico-chked"
                , unitCheckedClassName = "selected"
                // , basket = config.basket
                ;


            if($this.hasClass('ico-chked')){
                $this.removeClass(itemCheckedClassName);
            }else{
                add = true;
                $this.addClass(itemCheckedClassName);
                /*
                for(i = 0; i<$list.length; i++){
                    $unit = $($list[i]);
                    $unit.find('> .status > .ico-chk').removeClass('ico-chked');
                    $unit.removeClass('selected');
                    $unit.data('checked', false);
                }
                // config.basket = [];
                $this.removeClass('ico-chked');
                */
            /*
                for(i = 0; i<$list.length; i++){
                    $unit = $($list[i]);
                    room = $unit.data('room');
                    if(room){
                        $unit.find('> .status > .ico-chk').addClass('ico-chked');
                        $unit.addClass('selected');
                        $unit.data('checked', true);
                        /*
                        basket.push(
                            { 'id': GML.Room[room].id, 'node': $unit }
                        );
                        *./
                    }
                }
                $this.addClass('ico-chked');
                */
            }

            $list.each(function(index){
                unit = $(this);
                item = unit.find("[role=pick-MSG]"); // > .status > .ico-chk");
                if(add){
                    unit.addClass(unitCheckedClassName);
                    item.addClass(itemCheckedClassName);
                }else{
                    unit.removeClass(unitCheckedClassName);
                    item.removeClass(itemCheckedClassName);
                }
            });
        });

        $BOSS.on('click', '[role=pick-MSG]', function(){
            var $this = $(this)
                // , config = $this.closest('[role=bossMSG]').data('config')
                , $unit = $this.closest('tr')
                // , id = GML.Room[$unit.data('room')].id
                // , basket = config.basket
                ;

            $unit.toggleClass("selected");
            $this.toggleClass("ico-chked");
            /*
            if($unit.hasClass('selected')){
                $unit.removeClass('selected');
                $unit.data('checked', false);
                $this.removeClass('ico-chked');
                /*
                for(i=0; i<basket.length; i++){
                    if(basket[i].id === id){
                        basket.splice(i, 1);
                        break;
                    }
                }
                *./
            }else{
                $unit.addClass('selected');
                $unit.data('checked', true);
                $this.addClass('ico-chked');
                /*
                basket.push(
                    { 'id': id, 'node': $unit }
                );
                *./
            }
            */
        });

        /*
        $BOSS.on('click', '[role=view-MSG]', function(e){
            var $this = $(this)
                , paramLine = ''
                , param, p
                ;

            GML.Pipe.dig({
                'url': $this.attr('href')
            });
            e.preventDefault();
        });
        */

        that.fire($BOSS, config.first);
    }

    M.manage = function(c, $BOSS){
        var config = $BOSS.data("config")
            , key = c.key
            , that = M
            ;

        $BOSS.on("click", "[role~=" + key + "]", function(){
            var checkedItems, nextMove, noticeType, executeLine, afterExecute, notice, defaultNotice, beforeExecute, successExecute, failExecute, execute, $this, line, PM, noticeFormat, pmValue, pmType, room, otherParam, i, item
                , executeFN = c.execute
                , mid = config.namespace['mid']
                , $this = $(this)
                , scope = key.indexOf("-G-")>0 ? "group" : "unit"
                ;

            if(executeFN){
                // executeFN = execute["function"];
                beforeExecute = executeFN.before;
                successExecute = executeFN.success;
                failExecute = executeFN.fail;
            }

            // get all items checked
            if(scope === "group"){
                checkedItems = $("tr.selected", config.element.bodyTable);
                line = c.line;
                noticeFormat = c.notice;
            }else{
                checkedItems = $this.data("unit");
                if(!checkedItems){
                    checkedItems = $this.closest('tr');
                }
                pmValue = $this.data("pm");
                if(pmValue*1 < 0){
                    pmType = "minus";
                }else{
                    pmType = "plus";
                }
                PM = c[pmType];
                noticeFormat = PM.notice;
                line = PM.line;
            }
            if(!checkedItems.length){
                return;
            }

            executeLine = line + (line.indexOf("?") < 0 ? "?" : "&");
            checkedItems.each(function(index){
                executeLine += mid + "=" + that.recognize($(this), config.recognize) + "&";
            });
            executeLine = executeLine.slice(0, -1);
            /*
            var execute = function(){
                $.ajax({
                    url: line,
                    success: function(data){
                        if(data.status === 'success'){
                            that.manageGroup(type, config);
                        }else if(data.status === 'fail'){
                        }
                    }
                });
            }
            */

            room = $this.data("room");
            if(room){
                otherParam = GML.Room[room]["param"];
                if(otherParam){
                    for(i=0; i<otherParam.length; i++){
                        item = otherParam[i];
                        executeLine += "&" + item.key + "=" + item.value;
                    }
                }
            }

            execute = function(){
                $.ajax({
                    url: executeLine,
                    cache: false,
                    success: function(data){
                        if(data["status"] === "success"){
                            noticeType = "success";
                            afterExecute = successExecute;
                            defaultNotice = 13;
                            if(scope === "group"){
                                checkedItems.each(function(){
                                    var $this = $(this)
                                        , unit = $this.closest("tr")
                                        ;

                                    unit.removeClass("selected");
                                    $this.find("[role=pick-MSG]").removeClass("ico-chked");
                                });
                                config.element.pickAll.removeClass("ico-chked");
                                GML.Mole.shut();
                            }else{
                                $this.data("pm", pmValue * -1);
                            }
                        }else{
                            noticeType = "fail";
                            afterExecute = failExecute;
                            defaultNotice = 19;
                        }
                        if(noticeFormat){
                            notice = noticeFormat[noticeType];
                        }
                        if(!notice){
                            notice = T(defaultNotice);
                        }

                        that.notice(notice, config.element.notice);
                        if(afterExecute){
                            afterExecute($this, checkedItems, config);
                        }
                    }
                });
            }

            if(beforeExecute){
                beforeExecute(execute);
            }else{
                execute();
            }

            /*
            switch(type){
                case 'delete':
                    var $el = $('<div />', {
                        'data-t': type + '-sure-to',
                        'data-role': config.role
                    });
                    GML.Mole.panel({
                        'el': $el,
                        'fixed': 1,
                        'callback': {
                            'on': execute
                        }
                    });
                    return false;
                    break;
                default: 
                    execute();
            }
            */
        });
    /*
        var $BOSS = el
            , config = $BOSS.data('config')
            , recognize = config.recognize
            , that = M
            , mid = config.namespace['mid']
            ;

        switch(c.scope){
            case 'group':
                $BOSS.on('click', '[role~=' + c.key + ']', function(){
                    var // basket = config.basket
                        line = c.line
                        , type = c.type
                        , i, item
                        , param = ''
                        , basket = that.netIn($BOSS)
                        ;

                    GML.Mole.shut();
                    if(!basket){
                        return false;
                    }

                    if(line.indexOf('?') < 0){
                        line += '?';
                    }else{
                        line += '&';
                    }

                    /*
                    for(i=0; i<basket.length; i++){
                        item = basket[i];
                        param += that.recognize(item.node, recognize, mid) + '&';
                    }
                    *./
                    line = line + basket; // that.netIn($BOSS); // param;

                    var execute = function(){
                        $.ajax({
                            url: line,
                            success: function(data){
                                if(data.status === 'success'){
                                    that.manageGroup(type, config);
                                }else if(data.status === 'fail'){
                                }
                            }
                        });
                    }

                    switch(type){
                        case 'delete':
                            var $el = $('<div />', {
                                'data-t': type + '-sure-to',
                                'data-role': config.role
                            });
                            GML.Mole.panel({
                                'el': $el,
                                'fixed': 1,
                                'callback': {
                                    'on': execute
                                }
                            });
                            return false;
                            break;
                        default: 
                            execute();
                    }
                });
                break;
            case 'unit':
                $BOSS.on('click', '[role~=' + c.key + ']', function(){
                    var $this = $(this)
                        , $unit = $this.closest('tr')
                        , type = c.type
                        , i, line, genre
                        ;

                    if($this.data('unit')){
                        $unit = $this.data('unit');
                    }

                    if($this.hasClass('ico-chked')){
                        genre = c.black;
                    }else{
                        genre = c.white;
                    }

                    line = genre.line;

                    if(line.indexOf('?') < 0){
                        line += '?';
                    }else{
                        line += '&';
                    }

                    line = line + that.recognize($unit, recognize, mid);

                    var execute = function(){
                        $.ajax({
                            url: line,
                            // data: param,
                            success: function(data){
                                if(data.status === 'success'){
                                    that.manageUnit({
                                        'type': genre.type,
                                        // 'data': data.data,
                                        'el': $this
                                    });
                                }else if(data.status === 'fail'){
                                }
                            }
                        });
                    }

                    switch(genre.type){
                        case 'offline':
                        case 'delete':
                            var $el = $('<div />', {
                                'data-t': genre.type + '-sure-to',
                                'data-role': config.role
                            });
                            GML.Mole.panel({
                                'el': $el,
                                'fixed': 1,
                                'callback': {
                                    'on': execute
                                }
                            });
                            return false;
                            break;
                        default: 
                            execute();
                    }
                });
                break;
        }
    */
    }

    M.recognize = function(item, recognizer){
        var i
            , data = ""
            , room = GML.Room[item.data('room')]
            ;

        for(i=0; i<recognizer.length; i++){
            data += room[recognizer[i]] + '|';
        }
        data = data.slice(0, -1);

        return data;
    }

    M.manageUnit = function(c){
        var $this = c.el
            , config = $this.closest('[role=bossMSG]').data('config')
            , that = M
            , type = c.type
            ;

        switch(type){
            case 'trash':
            case 'delete':
            case 'offline':
            case 'online':
                var basket = config.basket
                    , i, line, mid, mtype, $pickAll, fruit
                    // , $unit = $this.data('unit')
                    , IDNS = config.namespace['mid']
                    , param = {}
                    ;

                /*
                if(type === 'online'){
                    $unit = $this.closest('tr');
                }else{
                    $unit = $this.data('unit');
                }
                for(i=0; i<basket.length; i++){
                    fruit = basket[i];
                    if(fruit.id === GML.Room[$unit.data('room')].id){
                        basket.splice(i, 1);
                    }
                }
                */
                $pickAll = config.element.pickAll;
                if($pickAll.hasClass('ico-chked')){
                    $pickAll.removeClass('ico-chked');
                }
                that.fire($this);
                that.notice({
                    'type': type,
                    'el': $this,
                    'status': 'success'
                });
                break;
            case 'unread':
                $this.closest('tr').addClass('unread');
                break;
            case 'read':
                $this.closest('tr').removeClass('unread');
                break;
            case 'bmark':
                break;
            case 'unbmark':
                break;
        }
        if($this.hasClass('ico-chked')){
            $this.removeClass('ico-chked');
        }else if(!$this.hasClass('ico-close-s2') && !$this.hasClass('ico-offline')){
            $this.addClass('ico-chked');
        }
        that.freshUnread();
    }

    M.manageGroup = function(t, c){
        var that = M
            , config = c
            , basket = config.basket
            , i, no, $sign
            , $pickAll = config.element.pickAll
            ;

        switch(t){
            case 'trash':
            case 'delete':
            case 'restore':
            case 'online':
                /*
                config.basket = [];
                */
                that.fire($pickAll);
                that.freshUnread();
                break;
            case 'unread':
                // no = 0;
                for(i = 0; i<basket.length; i++){
                    var $unit = basket[i]; // .node

                    $unit.find('> .status > .ico-read').removeClass('ico-chked');
                    $unit.find('> .status > .ico-chk').removeClass('ico-chked');
                    $unit.addClass('unread');
                    $unit.removeClass('selected');
                    $unit.data('checked', false);
                        /*
                        , $sign = $unit.find('> .status > .ico-read')
                        ;

                    if($sign.hasClass('ico-chked')){
                        $sign.removeClass('ico-chked');
                        $unit.addClass('unread');
                        // no++;
                    }
                    */
                }
                that.freshUnread(); // no, $unit);
                break;
            case 'read':
                // no = 0;
                for(i = 0; i<basket.length; i++){
                    var $unit = basket[i]; // .node

                    $unit.find('> .status > .ico-read').addClass('ico-chked');
                    $unit.find('> .status > .ico-chk').removeClass('ico-chked');
                    $unit.removeClass('selected');
                    $unit.data('checked', false);
                    /*
                        , $sign = $unit.find('> .status > .ico-read')
                        ;
                    if(!$sign.hasClass('ico-chked')){
                        $sign.addClass('ico-chked');
                        $unit.removeClass('unread');
                        // no++;
                    }
                    */
                }
                that.freshUnread();
                break;
            case 'unstar':
                for(i = 0; i<basket.length; i++){
                    var $unit = basket[i]; // .node;
                    $unit.find('> .status > .ico-sign').removeClass('ico-chked');
                    $unit.find('> .status > .ico-chk').removeClass('ico-chked');
                    $unit.removeClass('selected');
                    $unit.data('checked', false);
                }
                break;
            case 'star':
                for(i = 0; i<basket.length; i++){
                    var $unit = basket[i]; // .node;
                    $unit.find('> .status > .ico-sign').addClass('ico-chked');
                    $unit.find('> .status > .ico-chk').removeClass('ico-chked');
                    $unit.removeClass('selected');
                    $unit.data('checked', false);
                }
                break;
            /*
            case 'unbmark':
                for(i = 0; i<basket.length; i++){
                    var $unit = basket[i]; // .node;
                    $unit.find('> .status > .ico-fav').removeClass('ico-chked');
                    $unit.find('> .status > .ico-chk').removeClass('ico-chked');
                    $unit.removeClass('selected');
                }
                break;
                */
            case 'bmark':
                for(i = 0; i<basket.length; i++){
                    var $unit = basket[i]; // .node;
                    $unit.find('> .status > .ico-fav').addClass('ico-chked');
                    $unit.find('> .status > .ico-chk').removeClass('ico-chked');
                    $unit.removeClass('selected');
                    $unit.data('checked', false);
                }
                that.freshUnread();
                break;
        }
        
        config.basket = [];
        if($pickAll.hasClass('ico-chked')){
            $pickAll.removeClass('ico-chked');
        }
        that.notice({
            'type': t,
            'el': $pickAll,
            'status': 'success'
        });
    }

    M.print = function(t, c){
        return GML.Template.tube[t](c);
    }

    /*
    M.fill = function(d){
        var that = M
            , potion
            ;

        if(!d){
            return false;
        }
        potion = that.print(d);
        that.body.append($(potion));
    }
    */

    M.notice = function(message, $notice){
        var tipW, tipH, parentW;
    /*
        var config = c.el.closest('[role=bossMSG]').data('config')
            , that = M
            , message, tipW, tipH, parentW
            , $notice = config.element.notice
            ;

        switch(c.type){
            case 'trash':
                message = T(12, T(3));
                if(config.label === 'bmark'){
                    message = T(55, T(56));
                }
                break;
            case 'delete':
                message = T(55, T(56));
                break;
            case 'read':
                message = T(57, T(7));
                break;
            case 'unread':
                message = T(57, T(6));
                break;
            case 'star':
                message = T(57, T(5));
                break;
            case 'unstar':
                message = T(57, T(4));
                break;
            case 'restore':
                message = T(55, T(60));
                break;
            case 'bmark':
                message = T(55, T(67));
                break;
            case 'offline':
                $('#tab_offline_MSG').data('refresh', true);
                $('#tab_offline_MSG').data('refreshNO')();
                message = T(55, T(72));
                break;
            case 'online':
                $('#tab_approved_MSG').data('refresh', true);
                $('#tab_offline_MSG').data('refreshNO')();
                message = T(55, T(73));
                break;
            case 'renew':
                $('#tab_approved_MSG').data('refresh', true);
                $('#tab_offline_MSG').data('refreshNO')();
                message = T(55, T(112));
                break;
            default:
                message = T(13);
                break;
        }
        */

        $notice.html(message);
        $notice.show();
        tipW = $notice.outerWidth(true);
        tipH = $notice.outerHeight(true);
        parentW = $notice.parent().outerWidth(true);
        $notice.css({
            'top': 0,
            'left': (parentW - tipW) / 2
        });
        $notice.stop().fadeTo(1, 1);
        setTimeout(function(){
            $notice.fadeOut(1000);
        }, 1500);

    }

    M.fire = function(el, u, paging){
        var $BOSS = el.is('[role=bossMSG]') ? el : el.closest('[role=bossMSG]')
            , that = M
            , param = {}
            , search = ''
            , bodyTable, dataURL, searchS, i, item, key, value, url, template, potion, _param, config, baseDataUrlE, search_1, paramFilter, pageLine, pageNO, page, page_namespace, total
            ;

        if(!$BOSS.length){
            return false;
        }
        config = $BOSS.data('config');
        page_namespace = config.namespace["page"] || "pageNum";
        if(config.fire){
            return false;
        }
        bodyTable = config.element.bodyTable;
        dataURL = config.line;

        /* for page async */
        if(config.page){
            pageLine = config.page.line;
        }

        if(u){
            url = u;
        }else{
            url = config.url;
            paramFilter = that.paramFilter($BOSS);
            if(paramFilter){
                paramFilter = '&' + paramFilter;
            }
            search = location.search.substring(1) + paramFilter;
        }

        searchS = url.indexOf('?');
        if(searchS > -1){
            search_1 = url.slice(searchS + 1);
            if(search){
                search += '&' + search_1;
            }else{
                search += search_1;
            }
            url = url.substring(0, searchS);
        }

        searchS = dataURL.indexOf('?');
        if(searchS > -1){
            search_1 = dataURL.slice(searchS + 1);
            if(search){
                search += '&' + search_1;
            }else{
                search += search_1;
            }
            // url = url.substring(0, searchS);
        }

        if(search){
            _param = search.split('&');
            for(i=0; i<_param.length; i++){
                item = _param[i].split('=');
                key = item[0];
                value = item[1];
                if(key && value){
                    param[key] = decodeURIComponent(value.replace(/\+/g,' '));
                }
            }
        }

        if(dataURL.indexOf('?') > -1){
            dataURL = dataURL.substring(0, dataURL.indexOf('?'));
        }

        if(url.indexOf('?') > -1){
            url += decodeURIComponent($.param(param));
        }else{
            if($.param(param)){
                url += '?' + decodeURIComponent($.param(param));
            }
        }

        pageNO = parseInt(param[page_namespace]);
        // console.log(pageNO);
        if(!pageNO){
            pageNO = 1;
        }
        config.page['current'] = pageNO;
        if(pageLine){
            if(paging){
                that.pageNav($BOSS, config.page);
            }else{
                GML.Pipe.xhrQ(
                    $.ajax({
                        url: pageLine,
                        type: 'post',
                        data: param,
                        success: function(data){
                            if(data["status"] !== "success"){
                                return;
                            }
                            // config.page['current'] = pageNO;
                            config.page['total'] = data.page.total;
                            that.pageNav($BOSS, config.page);
                        }
                    })
                );
            }
        }

        GML.Pipe.xhrQ(
            $.ajax({
                url: dataURL,
                type: 'post',
                data: param,
                beforeSend: function(){
                    that.spinner($BOSS);
                    config['fire'] = 1;
                },
                success: function(data){
                    page = data.page || {};
                    total = page.total;
                    switch(data.status){
                        case 'nothing':
                            template = config.template.nothing;
                            break;
                        case 'noResult':
                            template = config.template.without;
                            break;
                        case 'success':
                            if(total || pageLine){
                                template = config.template.list;
                            }else{
                                template = config.template.without;
                            }
                            if(!paging && !pageLine){
                                // config.page['current'] = pageNO; // page.current;
                                config.page['total'] = page.total;
                            }
                            break;
                        case 'error':
                            return false;
                            break;
                    }

                    if(!pageLine){
                        that.pageNav($BOSS, page);
                    }

                    if($.param(param)){
                        param = $.param(param) + '&';
                    }else{
                        param = '';
                    }
                    potion = that.print(template, {
                        'label': config.label,
                        'role': config.role,
                        'param': param + 'mode=' + config.mode + '&returnURL=' + encodeURIComponent(url),
                        'back': config.url,
                        'data': data,
                        "addition": config.addition
                    });
                    bodyTable.html(potion);
                    that.spinner($BOSS);
                    config['fire'] = 0;
                    GML.Mole.hover(bodyTable);
                    if(data.status === 'success'){
                        that.shortcut(bodyTable);
                    }
                    GML.Pipe.historyManage(url);
                }
            })
        );

    }

    M.paramFilter = function(el){
        var config = el.data('config')
            , _param = config.element.filter.serialize().split('&')
            , param = ''
            , key, value, i, item
            ;

        for(i=0; i<_param.length; i++){
            item = _param[i].split('=');
            key = item[0];
            value = item[1];
            if(value && value !== 'MM-DD-YYYY'){
                param += key + '=' + value + '&';
            }
        }
        param = param.slice(0, -1);

        return param;
    }

    M.pageNav = function(el, d){
        var config = el.data('config') // that = M
            // , current = d.current
            , current = config.page.current
            , total = Math.ceil(d.total / 15)
            , pageAction = []
            , pageNav = []
            , url = config.url
            , pageSelect = ''
            , easyNav = ''
            , that = M
            , preClass, preLink, nextClass, nextLink, firstClass, firstLink, lastClass, lastLink, i, rangeBegin, rangeEnd, pageURL, param, roomNO_1
            ;

        if(total !== 0){
            // current = 0;
            if(url.indexOf('?') > -1){
                url += '&';
            }else{
                url += '?';
            }
            param = that.paramFilter(el);
            if(param){
                param += '&';
            }
            pageURL = url + param + config.namespace['page'] + '=';
            if(current < 2){
                preClass = 'prev-dis';
                preLink = '<span></span>';
                firstClass = 'first-dis';
                firstLink = preLink;
            }else{
                preClass = 'prev';
                preLink = '<a href="' + pageURL + (current - 1) + '" title="pre" role="page-MSG"></a>';
                firstClass = 'first';
                firstLink = '<a href="' + pageURL + '1" title="first" role="page-MSG"></a>';
            }
            if(current >= total){
                nextClass = 'next-dis';
                nextLink = '<span></span>';
                lastClass = 'last-dis';
                lastLink = nextLink;
            }else{
                nextClass = 'next';
                nextLink = '<a href="' + pageURL + (current + 1) + '" title="next" role="page-MSG"></a>';
                lastClass = 'last';
                lastLink = '<a href="' + pageURL + total + '" title="last" role="page-MSG"></a>';
            }
            pageAction = [
                '<li class="' + preClass + '">',
                    preLink,
                '</li>',
                '<li class="' + nextClass + '">',
                    nextLink,
                '</li>',
            ];
            if(current - 2 < 1){
                rangeBegin = 1;
            }else{
                rangeBegin = current - 2;
            }
            if(rangeBegin + 4 > total){
                rangeEnd = total;
            }else{
                rangeEnd = rangeBegin + 4;
            }
            for(i=rangeBegin; i<=rangeEnd; i++){
                if(i === current){
                    easyNav += '<li><span>' + i + '</span></li>';
                }else{
                    easyNav += '<li><a href="' + pageURL + i + '" role="page-MSG">' + i + '</a></li>';
                }
            }
            roomNO_1 = GML.Room.roomNO;
            GML.Room[roomNO_1] = {
                'current': current,
                'total': total,
                'url': pageURL
            }
            GML.Room.roomNO++;
            pageNav = [
                '<div class="select-box">',
                    '<div class="txt" role="mole-t" data-t="page-list-MSG" data-room="' + roomNO_1 + '"><span></span><em>' + current + '/' + total + '</em></div>', 
                '</div>',
                '<div class="page-wrap">',
                    '<ul class="page">',
                        '<li class="' + firstClass + '">',
                            firstLink,
                        '</li>',
                        '<li class="' + preClass + '">',
                            preLink,
                        '</li>',
                        easyNav,
                        '<li class="' + nextClass + '">',
                            nextLink,
                        '</li>',
                        '<li class="' + lastClass + '">',
                            lastLink,
                        '</li>',
                    '</ul>',
                '</div>',
                '<span class="all-num">' + T(11, total) + '</span>'
            ];
            if(config.mode === 'SUBBL' && config.role === 'mvo'){
                pageNav = [
                    '<div class="page-wrap">',
                        '<ul class="page">',
                            '<li class="' + preClass + '">',
                                preLink,
                            '</li>',
                            easyNav,
                            '<li class="' + nextClass + '">',
                                nextLink,
                            '</li>',
                        '</ul>',
                    '</div>',
                ];
            }
        }
        config.element.pageNavS.html(pageAction.join(''));
        config.element.pageNav.html(pageNav.join(''));
    }

    M.shortcut = function(el){
        var config = el.closest('[role=bossMSG]').data('config')
            , bodyTable, $SC, units, i, item, SC
            ;

        if(!config.shortcutPanel){
            return false;
        }
        bodyTable = config.element.bodyTable;
        units = bodyTable.children();
        SC = config.shortcutPanel;

        $SC = config.element.SC;

        if(!$SC){
            $SC = $('<span />', {
                'class': SC['class'],
                'role': SC['role'],
                'data-pm': 1,
                'style': 'position:absolute; display:none'
            });
            $SC.insertAfter(bodyTable.closest('table'));

            $SC.hover(
                function(){
                    clearTimeout(config.TO.SC);
                },
                function(){
                    $(this).hide();
                }
            );
            config.element['SC'] = $SC;
        }

        for(i=0; i<units.length; i++){
            item = $(units[i]);
            item.hover(
                function(){
                    var $this = $(this)
                        , position = $this.position()
                        ;

                    clearTimeout(config.TO.SC);
                    $SC.show();
                    $SC.css({
                        'top': position.top,
                        'left': position.left + $this.outerWidth(true) + 1
                    });
                    $SC.data('unit', $this);
                },
                function(){
                    config.TO.SC = setTimeout(function(){
                        $SC.hide();
                    }, 700);
                }
            );
        }
    }

    M.freshUnread = function(n, el){
        var that = M
            , unreadNO = that.unreadNO
            , $node
            ;

        if(!unreadNO){
            return false;
        }
        $node = $('#' + unreadNO.node);
        $.ajax({
            url: unreadNO.line,
            beforeSend: function(){
                // that.spinner($BOSS);
            },
            success: function(data){
                if(data.status){
                    var no = data.unreadNO
                        , $reminder = $('')
                        ;

                    if(unreadNO.role === 'message'){
                        $reminder = $('#newMsgReminder');
                    }
                    if(no < 1){
                        $node.hide();
                        $reminder.addClass('hidden');
                    }else{
                        $node.show();
                        $node.html('(' + no + ')');
                        $reminder.removeClass('hidden');
                    }
                }
            }
        });
    }

    M.spinner = function(el){
        var config = el.data('config')
            , element = config.element
            , bodyTable = element.bodyTable
            , $spinner = bodyTable.data('spinner')
            , position, height, BPtop
            ;

        if($spinner && !$spinner.is(':hidden')){
            $spinner.hide();
            return false;
        }
        if(!$spinner){
            $spinner = $('<div />', {
                'class': 'spinnerCenter'
            });
            $spinner.insertAfter(bodyTable.closest('table'));
            bodyTable.data('spinner', $spinner);
        }
        position = bodyTable.position();
        height = bodyTable.outerHeight(true) - 2;
        if(height > 640){
            BPtop = '100px';
        }else{
            BPtop = 'center';
        }
        $spinner.css({
            'top': position.top + 1,
            'left': position.left + 1,
            'width': bodyTable.outerWidth(true) - 2,
            'height': bodyTable.outerHeight(true) - 2,
            'backgroundPosition': 'center ' + BPtop
        });
        $spinner.show();
    }

    M.UI = function(el){
        var checkbox = $('[role~=checkbox]', el)
            , i, $item, $input
            ;

        for(i=0; i<checkbox.length; i++){
            $item = $(checkbox[i]);
            $input = $('<input />', {
                'type': 'checkbox',
                'name': $item.data('name'),
                'value': true,
                'class': 'hide'
            });
            $item.data('input', $input);
            $input.insertAfter($item);
            if($item.hasClass('ico-chked')){
                $input[0].checked = true;
            }
        }
    }

    /*
    M.pickUp = function(el){
        var c = el.data('config')
            , $list = c.element.bodyTable.children()
            // , recognize = c.recognize
            // , mid = c.namespace['mid']
            , that = M
            , $unit, i
            , param = ''
            ;

        for(i=0; i<$list.length; i++){
            $unit = $($list[i]);
            if($unit.data('checked')){
            // if($unit.hasClass('selected')){
                basket.push($unit);
                // c.basket.push($unit); // {});
                // param += that.recognize($unit, recognize, mid) + '&';
            }
        }

        // return param.slice(0, -1);
        return param.slice(0, -1);
    }
    */

    M.init();
    return M;

})();

